package com.encyclopedia.handler;

import com.encyclopedia.result.exenum.RequestException;
import com.encyclopedia.utils.JsonSerializeUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * SpringSecurity自定义异常处理器
 *
 * @author by 春风能解释
 * <p>
 * 2024/3/27
 */
public class ExceptionHandler {
    /**
     * 针对非法授权的异常处理
     */
    @Component
    public static class AuthenticationPrint implements AuthenticationEntryPoint {

        /**
         * 打印错误信息
         *
         * @param request       请求
         * @param response      响应
         * @param authException 授权异常
         */
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
            JsonSerializeUtils.responseWriter(RequestException.FORBIDDEN, response);
        }
    }

    /**
     * 针对非法访问的异常处理
     */
    @Component
    public static class AccessDeniedPrint implements AccessDeniedHandler {

        /**
         * 非法访问响应体打印
         *
         * @param request               请求体
         * @param response              响应体
         * @param accessDeniedException 非法访问异常
         * @throws IOException IO异常
         */
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
            JsonSerializeUtils.responseWriter(RequestException.UNAUTHORIZED, response);
        }
    }
}
